package ControlLayer;


import java.util.ArrayList;

import DBLayer.DBInvoice;
import DBLayer.DBOrderLine;
import DBLayer.DBProduct;
import DBLayer.DBSalesOrder;
import DBLayer.DbConnection1;
import DBLayer.IFDBInvoice;
import DBLayer.IFDBOrderLine;
import DBLayer.IFDBProduct;
import DBLayer.IFDBSalesOrder;
import ModelLayer.*;
public class OrderCtr {
	
      private SalesOrder order;
      
    private static OrderCtr instance;
	
	/**
	 * Look if the product exists in the data base. If found,check if available and add to order.
	 * If not found -return false, if not enough of it throw exception.
	 * @param id
	 * @param qunt
	 * @return
	 */
      
      private OrderCtr (){
    	  order=new SalesOrder();
      }
      
      public static OrderCtr getInstance()
      {
    	  if(instance==null)
    		  instance=new OrderCtr();
    	  
		return instance;
    	  
      }
      
      
      
	public boolean findProduct(int id,int quant)
	{
		DBProduct dbProduct = new DBProduct();
		Product product =  dbProduct.findProduct(id, false);
		int amount = product.getCurentStock();
		
		if(amount >= quant ){
			
			
			product.setCurentStock(amount-quant);
			OrderLine orderLine = new OrderLine(product, quant);
			order.addOrderLine(orderLine);
			orderLine.setSalesOrder(order);
			return true;
			
		}
	
			return false;
		
	}
	
	
	/**
	 *Attach the given customer to the order.
	 *
	 */
	public void addToOrder(Customer customer)
	{
		order.setCustomer(customer);
		
	}
	
	public void enterDDate(String date){
		order.setDeliveryDate(date);
		
	}
	
	
	/**
	 * Finalize the order by creating the invoice and saving SalesOrder, OrderLines, Invoice in the data base
	 * additionally update product quantity.
	 * @return
	 */
	public boolean finilizeOrder()
	{
		
		Invoice invoice = new Invoice();
		invoice.setfAmount(order.getAmountAfterTaxes());
		order.setInvoice(invoice);
		ArrayList<OrderLine> orderLines=new ArrayList<OrderLine>();
		orderLines=order.getOrderLines();
		IFDBSalesOrder dbSalesOrder = new DBSalesOrder();
		IFDBOrderLine dbOrderLine= new DBOrderLine();
		IFDBInvoice dbInvoice=new DBInvoice();
		IFDBProduct dbProduct= new DBProduct();
		
		 DbConnection1.startTransaction();
		 
		try {
			dbInvoice.insert(invoice);
			dbSalesOrder.insertSalesOrder(order);
			for(OrderLine line: orderLines)
			{
				dbOrderLine.insertOrderLine(line);
				dbProduct.updateProduct(line.getProduct());
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		 if (!DbConnection1.commitTransaction())           
             DbConnection1.rollbackTransaction();
		
		return true;
	}

}